import { getArticlesInWeb } from '@/api/api';
import { articleType, queryParamsType } from '@/utils/model';
import React, { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import BaseInfoComponent from './base-info';

export default function ScrollList({
  list = [],
  pageInfo,
}: {
  list?: articleType[];
  pageInfo?: queryParamsType;
}) {
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrent] = useState(pageInfo?.current || 0);
  const [total, setTotal] = useState(pageInfo?.total || 0);
  const [data, setData] = useState<articleType[]>(list);
  useEffect(() => {
    if (!pageInfo) {
      loadMoreData();
    }
  }, []);
  const loadMoreData = async () => {
    if (loading) {
      return;
    }
    try {
      setLoading(true);
      const result = await getArticlesInWeb({ current: currentPage + 1 });
      setCurrent(currentPage + 1);
      setData([...data, ...result.data]);
      setTotal(result.total);
    } catch (e) {}
    setLoading(false);
  };

  return (
    <div className="custom-card base-card bg-white  margin-bottom-20 flex-1 flex flex-col">
      <InfiniteScroll
        dataLength={data.length}
        next={loadMoreData}
        hasMore={data.length < (total || 0)}
        scrollableTarget="scrollableDiv"
        loader={undefined}
      >
        {data.map((item) => (
          <BaseInfoComponent
            id={item.id}
            key={item.id}
            desc={item.description}
            title={item.title}
            time={'发布时间：' + item.updateAt}
          />
        ))}
      </InfiniteScroll>
    </div>
  );
}
